package the.one.mzitu.presenter;

import android.content.Context;

import com.rxjava.rxlife.RxLife;

import java.io.File;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import rxhttp.wrapper.param.RxHttp;
import rxhttp.wrapper.param.RxHttpNoBodyParam;
import the.one.base.Interface.OnError;
import the.one.base.ui.presenter.BaseDataPresenter;
import the.one.base.util.DownloadUtil;
import the.one.base.util.FileDirectoryUtil;
import the.one.base.util.ShareUtil;
import the.one.mzitu.bean.Mzitu;
import the.one.mzitu.constant.MzituConstant;
import the.one.mzitu.util.MzituParseUtil;


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛

/**
 * @author The one
 * @date 2019/3/5 0005
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
public class MzituPresenter extends BaseDataPresenter<Mzitu> {

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";

    public void getCategoryData(String url, final int page) {
        final String fakeRefer = MzituConstant.WELFARE_BASE_URL + url + "/";
        if (MzituConstant.isNoDetail(url)) {
            url = fakeRefer + "/comment-page-" + page + "/#comments";
        } else {
            url = fakeRefer + "page/" + page + "/";
        }
        get(url, s -> {
            onComplete(MzituParseUtil.parseMzituCategory(s, fakeRefer));
        });
    }


    public void getDetailData(final String url) {
        get(url, s -> {
            onComplete(MzituParseUtil.parseMzituDetail(s, url));
            getView().onNormal();
        });
    }

    private void get(String url, Consumer<String> onNext) {
        get(url,url)
                .asString()
                .as(RxLife.asOnMain(this))
                .subscribe(onNext, (OnError) error -> {
                    //请求失败
                    onFail(error.getErrorMsg());
                });
    }


    public void downloadFile(final Context context, final int position, boolean isShare, final List<Mzitu> mzitus) {
        Mzitu data = mzitus.get(position);
        final int total = mzitus.size();
        //文件存储路径
        final String destPath = checkFileExists(FileDirectoryUtil.getDownloadPath() + File.separator + "Mzitu" + File.separator + data.getTitle());
        String fileName = (isShare ? "share" : "download" + "_mzitu_") + position + DownloadUtil.getFileSuffix(data.getImageUrl(), false);
        String path = isShare ? FileDirectoryUtil.getCachePath() : destPath + File.separator + fileName;
        get(data.getImageUrl(), data.getRefer())
                .asDownload(path, AndroidSchedulers.mainThread(), progress -> {
                    String tips = isShare ? "分享中" : ("下载中" + position + "/" + total);
                    getView().showProgressDialog(position, total, tips);
                })
                .as(RxLife.asOnMain(this)) //感知生命周期
                .subscribe(s -> {//s为String类型，这里为文件存储路径
                    //下载完成，处理相关逻辑
                    if (isShare) {
                        getView().hideProgressDialog();
                        ShareUtil.shareImageFile(context, new File(s), "开车了~ 系好安全带");
                    } else {
                        if (position == total - 1) {
                            getView().hideProgressDialog();
                            getView().showToast("已下载到：" + destPath);
                        } else {
                            int po = position + 1;
                            downloadFile(context, po, isShare, mzitus);
                        }
                    }
                }, (OnError) error -> {
                    //下载失败，处理相关逻辑
                    if (isShare || position == total - 1) {
                        getView().hideProgressDialog();
                        showFailTips(error.getErrorMsg());
                    } else {
                        int po = position + 1;
                        downloadFile(context, po, isShare, mzitus);
                    }
                });
    }

    private RxHttpNoBodyParam get(String url, String refer) {
        return RxHttp.get(url)
                .addHeader("Referer", refer)
                .addHeader("User-Agent", USER_AGENT);
    }


    private String checkFileExists(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        return path;
    }

}
